#pragma once
#include<iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include<unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <string.h>
class Addr
{
public:
    //网络转主机
    Addr(struct sockaddr_in &addr)
    {
        SetAddr(addr);
    }
    //主机转网络
    Addr(std::string ip,uint16_t port)
    :_ip(ip),_port(port)
    {
        memset(&_addr,0,sizeof(_addr));
        inet_pton(AF_INET,_ip.c_str(),&(_addr.sin_addr));
        _addr.sin_family=AF_INET;
        _addr.sin_port=htons(_port);
    }
    Addr(uint16_t port)
    :_port(port)
    {
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_addr.s_addr=INADDR_ANY;
        _addr.sin_family=AF_INET;
        _addr.sin_port=htons(_port);
    }
    void SetAddr(struct sockaddr_in &addr)
    {
        _addr=addr;
        _addr.sin_family=AF_INET;
        _port=ntohs(_addr.sin_port);
        char buffer[1024];
        inet_ntop(AF_INET,&(_addr.sin_addr),buffer,sizeof(_addr));
        _ip=buffer;
    }
    bool operator==(Addr& peer)
    {
        return _port==peer.Port()&&_ip==peer.Ip();
    }
    uint16_t Port()
    {
        return _port;
    }
    std::string Ip()
    {
        return _ip;
    }
    struct sockaddr_in& Sockaddr()
    {
        return _addr;
    }
    struct sockaddr_in* pSockaddr()
    {
        return &_addr;
    }
    socklen_t Socklen()
    {
        return sizeof(_addr);
    }
    std::string GetAddr()
    {
        return _ip+"."+ std::to_string(_port);
    }
    ~Addr()
    {}
private:
    uint16_t _port;
    std::string _ip;//点分十进制风格的ip
    struct sockaddr_in _addr;
};